// Copyright 2011 Alex K (wtwf.com) All rights reserved.

control = {};
control.onLoad = function() {
  d('starting');
  // alert('loaded!');
  $('#prev').bind('click', control.prev);
  $('#play').bind('click', control.playPause);
  $('#next').bind('click', control.next);


  $('#volup').bind('click', function() { $.ajax({url: '/do/volup'});});
  $('#voldown').bind('click', function() { $.ajax({url: '/do/voldown'});});

  // hide the URL bar!
  // http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/
  /mobile/i.test(navigator.userAgent) && setTimeout(function () {
    window.scrollTo(0, 1);
  }, 1000);

  // TODO(ark) set up the sliders:
  // https://github.com/alexgibson/WKSlider/blob/master/index.html

  $('#volume_handle').bind('drag touchstart touchmove', control.volumeSlide);

  d('ready to roll!');
};

control.volumeSlide = function(e) {
  e.preventDefault();
  var touchX;

  if (e.type == 'drag') {
    touchX = e.originalEvent.pageX;
    if (touchX < 1 ) {
      return false;
    }
    e = e.originalEvent;
    // console.log([e.clientX, e.layerX, e.offsetX, e.pageX, e.x, e.screenX].join(' : '));
  } else {
    // Only deal with one finger
    touchX = e.originalEvent.changedTouches[0].pageX;
  }
  $(this).css({left: touchX});
  return false;
};

control.playPause = function() {
  // alert('PlayPause: ' + $('#play'));
  if ($('#play').attr('src') == 'play.png') {
    $('#play').attr('src', 'pause.png');
    $.ajax({url: '/do/play'});
  } else {
    $('#play').attr('src', 'play.png');
    $.ajax({url: '/do/pause'});
  }
};

control.next = function() {
  $.ajax({url: '/do/next'});
};

control.prev = function() {
  $.ajax({url: '/do/prev'});
};


function d(msg) {
  console.log(msg);
  $('#debug').attr('value', msg + '\n' + $('#debug').attr('value'));
};
